<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Promise</title>


</head>
<body>

</body>
<script src="../../lib/jquery.js"></script>
<script src="../../lib/mock.js"></script>
<script src="js/mock/index.js"></script>
<script>

    /**
     *  promise
     *     目的 ：消解回调地狱
     *
     *
     * */

    /**
     *   1.简单使用
     * */
    function testPromise() {
        return new Promise((resolve, reject) => {

            let result = 45;
            resolve(result);
            let err = '';
            reject(err);
        })
    }


    // testPromise().then((res)=>{
    //     console.log(res);
    // })


    /**
     *  2. 异步模拟
     * */

    function testPromise2({name, age}) {

        return new Promise((resolve) => {

            setTimeout(function () {
                resolve(name + age);
            }, 2000);
        })
    }


  /*  testPromise2({
        name:'Mat',
        age:34
    }).then((res)=>{
         console.log(res);
    })
*/
    /**
     *  3. 处理ajax
     * */


     $.ajax({
          url:'http://test.org/emp/list',
          method:'get',
          dataType:'json',
          success:function (data) {
              console.log(data);
          }
     })


    function ajax({url,method='get'}) {

          return new Promise((resolve)=>{
              $.ajax({
                  url:url,
                  method:method,
                  dataType:'json',
                  success:function (data) {
                       resolve(data);
                  }
              })

          })
    }



    ajax({
        url:'http://test.org/emp/list',
        method:'get'
    }).then((res)=>{
        console.log(data);
    })

    var that = this;

    ajax({
        url:'http://test.org/emp/list',
        method:'get'
    }).then(function () {

        console.log(that.message);
    })
</script>
</html>